namespace TSL.Utility.Json
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Text;

    public class IDictionaryConverter : IJavaScriptConverter
    {
        private string clientType = "Ajax.Web.Dictionary";

        public IDictionaryConverter()
        {
            base.m_AllowInheritance = true;
            base.m_serializableTypes = new Type[] { typeof(IDictionary), typeof(IDictionary<,>) };
            base.m_deserializableTypes = base.m_serializableTypes;
        }

        public override object Deserialize(IJavaScriptObject o, Type t)
        {
            JavaScriptObject obj2 = o as JavaScriptObject;
            if (obj2 == null)
            {
                throw new NotSupportedException();
            }
            if (!(obj2.Contains("keys") && obj2.Contains("values")))
            {
                throw new NotSupportedException();
            }
            IDictionary dictionary = (IDictionary) Activator.CreateInstance(t);
            ParameterInfo[] parameters = t.GetMethod("Add").GetParameters();
            Type parameterType = parameters[0].ParameterType;
            Type type = parameters[1].ParameterType;
            JavaScriptArray array = obj2["keys"] as JavaScriptArray;
            JavaScriptArray array2 = obj2["values"] as JavaScriptArray;
            for (int i = 0; (i < array.Count) && (i < array2.Count); i++)
            {
                object key = JavaScriptDeserializer.Deserialize(array[i], parameterType);
                object obj4 = JavaScriptDeserializer.Deserialize(array2[i], type);
                dictionary.Add(key, obj4);
            }
            return dictionary;
        }

        public override string GetClientScript()
        {
            if (Utility.Settings.OldStyle.Contains("renderJsonCompliant"))
            {
                return "";
            }
            return (JavaScriptUtil.GetClientNamespaceRepresentation(this.clientType) + "\r\n" + this.clientType + " = function(type,items) {\r\n\tthis.__type = type;\r\n\tthis.keys = [];\r\n\tthis.values = [];\r\n\r\n\tif(items != null && !isNaN(items.length)) {\r\n\t\tfor(var i=0; i<items.length; i++)\r\n\t\t\tthis.add(items[i][0], items[i][1]);\r\n\t}\r\n};\r\nObject.extend(" + this.clientType + ".prototype, {\r\n\tadd: function(k, v) {\r\n\t\tthis.keys.push(k);\r\n\t\tthis.values.push(v);\r\n\t\treturn this.values.length -1;\r\n\t},\r\n\tcontainsKey: function(key) {\r\n\t\tfor(var i=0; i<this.keys.length; i++) {\r\n\t\t\tif(this.keys[i] == key) return true;\r\n\t\t}\r\n\t\treturn false;\r\n\t},\r\n\tgetKeys: function() {\r\n\t\treturn this.keys;\r\n\t},\r\n\tgetValue: function(key) {\r\n\t\tfor(var i=0; i<this.keys.length && i<this.values.length; i++) {\r\n\t\t\tif(this.keys[i] == key){ return this.values[i]; }\r\n\t\t}\r\n\t\treturn null;\r\n\t},\r\n\tsetValue: function(k, v) {\r\n\t\tfor(var i=0; i<this.keys.length && i<this.values.length; i++) {\r\n\t\t\tif(this.keys[i] == k){ this.values[i] = v; }\r\n\t\t\treturn i;\r\n\t\t}\r\n\t\treturn this.add(k, v);\r\n\t},\r\n\ttoJSON: function() {\r\n\t\treturn AjaxPro.toJSON({__type:this.__type,keys:this.keys,values:this.values});\r\n\t}\r\n}, true);\r\n");
        }

        internal static bool IsInterfaceImplemented(object obj, Type interfaceType)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            return (obj.GetType().FindInterfaces(delegate (Type type, object filter) {
                return (type.Name == ((Type) filter).Name) && (type.Namespace == ((Type) filter).Namespace);
            }, interfaceType).Length == 1);
        }

        public override string Serialize(object o)
        {
            StringBuilder sb = new StringBuilder();
            this.Serialize(o, sb);
            return sb.ToString();
        }

        public override void Serialize(object o, StringBuilder sb)
        {
            IDictionary dictionary = o as IDictionary;
            if (dictionary == null)
            {
                throw new NotSupportedException();
            }
            IDictionaryEnumerator enumerator = dictionary.GetEnumerator();
            enumerator.Reset();
            bool flag = true;
            bool flag2 = enumerator.MoveNext();
            Type type = o.GetType();
            if (!Utility.Settings.OldStyle.Contains("renderJsonCompliant"))
            {
                sb.Append("new ");
                sb.Append(this.clientType);
                sb.Append("(");
                sb.Append(JavaScriptSerializer.Serialize(type.FullName));
                sb.Append(",");
            }
            sb.Append("[");
            if (flag2)
            {
                do
                {
                    if (flag)
                    {
                        flag = false;
                    }
                    else
                    {
                        sb.Append(",");
                    }
                    sb.Append('[');
                    sb.Append(JavaScriptSerializer.Serialize(enumerator.Key));
                    sb.Append(',');
                    sb.Append(JavaScriptSerializer.Serialize(enumerator.Value));
                    sb.Append(']');
                }
                while (enumerator.MoveNext());
            }
            sb.Append("]");
            if (!Utility.Settings.OldStyle.Contains("renderJsonCompliant"))
            {
                sb.Append(")");
            }
        }

        public override bool TrySerializeValue(object o, Type t, StringBuilder sb)
        {
            if (IsInterfaceImplemented(o, typeof(IDictionary)))
            {
                this.Serialize(o, sb);
                return true;
            }
            return base.TrySerializeValue(o, t, sb);
        }
    }
}

